<!--
 * @Author: your name
 * @Date: 2021-06-23 17:10:54
 * @LastEditTime: 2021-06-24 08:55:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \totiao\src\views\Search\SearchResult.vue
-->
<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
      fixed
    />
    <!-- 循环渲染文章的item 组件 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <Artitem
        v-for="item in artList"
        :key="item.art_id"
        :article="item"
        :closable="false"
      ></Artitem>
    </van-list>
  </div>
</template>

<script>
// 按需导入api接口
import { getSuggResultApi } from '../../api/searchApi'
// 导入文章的item组件
import Artitem from '../../components/Artitem/Artitem.vue'

export default {
  name: 'SearchResult',
  props: ['kw'],
  data () {
    return {
      // 默认第1页数据
      page: 1,
      artList: [],
      loading: false,
      finished: false
    }
  },
  created () {
    this.initSearchResult()
  },
  methods: {
    // 初始化搜索结果
    async initSearchResult () {
      const { data: res } = await getSuggResultApi(this.kw, this.page)
      console.log(res)
      if (res.message === 'OK') {
        // this.artList = res.data.results
        // 上拉刷新
        // this.artList = [...旧数据,...新数据]
        this.artList = [...this.artList, ...res.data.results]
        // 重置loading 的值为false ,否则无法发送下一页的数据请求
        this.loading = false

        // 判断啥时候没有数据
        if (res.data.results.length === 0) {
          // 证明没有下一页的数据了
          this.finished = true
        }
      }
    },
    // 快到底部的时候,会自动调用这个函数
    onLoad () {
      console.log('触发了load事件')
      // 先让页面值自增
      this.page += 1
      // 在调用initSearchResult方法
      this.initSearchResult()
    }
  },
  components: {
    Artitem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
